package session.stateless.FRM;

import entity.CRM.Customer;
import entity.CRM.SaleOrder;
import entity.FRM.CustomerInvoice;
import entity.SCM.DeliveryOrder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import session.stateless.CRM.SaleOrderBeanLocal;

@Stateless
public class CustomerInvoiceBean implements CustomerInvoiceBeanLocal {
    
    @PersistenceContext 
    private EntityManager em; 
    @EJB
    SaleOrderBeanLocal saleOrderBeanLocal;            
    
    DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
    
    @Override
    public Long createCustomerInvoice(Long deliveryOrderId) {
        DeliveryOrder deliveryOrder =em.find(DeliveryOrder.class, deliveryOrderId);
        Customer customer = deliveryOrder.getSaleOrder().getCustomer();
        SaleOrder saleOrder = deliveryOrder.getSaleOrder();
        
        Double amount= deliveryOrder.getPickingOrder().getTotalPrice();
        if (saleOrderBeanLocal.havingCashInAdvance(saleOrder.getId()))
        {
            amount-=saleOrder.getCashInAdvance().getCashInAdvanceAmount();
        }
        
        CustomerInvoice customerInvoice = new CustomerInvoice();
        Date date = new Date();
        customerInvoice.setCustomerInvoiceDate(dateFormat.format(date));
        customerInvoice.setSaleOrder(saleOrder);
        customerInvoice.setCustomerInvoiceAmount(amount);
        em.persist(customerInvoice);
        
        customer.getCustomerInvoices().add(customerInvoice);
        saleOrder.getCustomerInvoices().add(customerInvoice);
        em.flush();
        
        return customerInvoice.getCustomerInvoiceId();
    }

    @Override
    public List<CustomerInvoice> getAllCustomerInvoices() {
        Query query = em.createQuery("SELECT c FROM CustomerInvoice c");
        List<CustomerInvoice> customerInvoices = query.getResultList();
        return customerInvoices;
    }
}
